package com.example.lsn_opengles713;

import android.opengl.GLU;

import com.example.lsn_opengles713.util.BufferUtil;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * 光照
 */
public class MyLightingRenderer1 extends AbstractMyRenderer {
	
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		gl.glClearColor(0f, 0f, 0f, 1f);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnable(GL10.GL_DEPTH_TEST);
	}
	/**
	 * 2.
	 */
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		gl.glViewport(0, 0, width, height);
		ratio = (float)width / (float)height;
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		gl.glFrustumf(-ratio, ratio, -1, 1, 3f, 7f);
	}
	public void onDrawFrame(GL10 gl) {
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT|GL10.GL_DEPTH_BUFFER_BIT);
		gl.glColor4f(0f, 0f, 1f, 1f);
		
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
		GLU.gluLookAt(gl, 0, 0, 5, 0, 0, 0, 0, 1, 0);
		
		gl.glRotatef(xrotate, 1, 0, 0);
		gl.glRotatef(yrotate, 0, 1, 0);
		
		//单调模式
		gl.glShadeModel(GL10.GL_FLAT);
		
		/******************** 光照 *******************************/
		//启用光照
		if(enableLighting)
			gl.glEnable(GL10.GL_LIGHTING);
		else
			gl.glDisable(GL10.GL_LIGHTING);
			
		//设置全局环境光
		float[] global_ambient = {
			global$ambient$r,
			global$ambient$g,
			global$ambient$b,
			global$ambient$a,
		};
		gl.glLightModelfv(GL10.GL_LIGHT_MODEL_AMBIENT, BufferUtil.arr2FloatBuffer(global_ambient));
		
		//1.设置材料的反射率(环境光和散射光)
		float[] matrial_ambient_diffuse = {
			material$ambientanddiffuse$r,
			material$ambientanddiffuse$g,
			material$ambientanddiffuse$b,
			material$ambientanddiffuse$a,
		};
		gl.glLightfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT_AND_DIFFUSE, BufferUtil.arr2FloatBuffer(matrial_ambient_diffuse));
		
		//颜色追踪 glColor();
		if(enableColorMatrial)
			gl.glEnable(GL10.GL_COLOR_MATERIAL);
		else
			gl.glDisable(GL10.GL_COLOR_MATERIAL);
		//openGLES是固定的将环境光合散射光最终颜色
		//openGL:glColorMatrial();
		gl.glColor4f(color$r, color$g, color$b,color$a);
		
		//光源0
		if(enableLight0)
			gl.glEnable(GL10.GL_LIGHT0);
		else
			gl.glDisable(GL10.GL_LIGHT0);
		//环境光
		float[] light0_ambient = {
			light0$ambient$r,
			light0$ambient$g,
			light0$ambient$b,
			light0$ambient$a,
		};
		gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, BufferUtil.arr2FloatBuffer(light0_ambient));
		
		//散射光
		float[] light0_diffuse = {
				light0$diffuse$r,
				light0$diffuse$g,
				light0$diffuse$b,
				light0$diffuse$a,
			};
		gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, BufferUtil.arr2FloatBuffer(light0_diffuse));
		
		//光源 0-位置,1.0表示光源就在此地
		float[] light0pos = {
			light0$pos$x,
			light0$pos$y,
			light0$pos$z,
			1.0f
		};
		gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, BufferUtil.arr2FloatBuffer(light0pos));
		
		BufferUtil.drawSphere(gl, 0.6f, 8, 8);
	}
}